import { defineStore } from 'pinia';
import { isEmpty, get } from 'lodash-es';
import { handleCommonRes } from '../utils/resolver.js';
import { setFavicon } from '../utils/domUtils.js';
import { USER_BUTTONS_KEY, USER_INFO_KEY } from '../config/index.js';
import storage from '../utils/storage.js';
import vueGlobal from '../vueGlobal.js';
import { useStaticDataStore } from './staticData.js';
import { getStoreId } from './utils.js';
import { setDocumentTitle } from '@gis/lib/utils/domUtils.js';
import { tokenDecrypt } from '@gis/lib/api/index.js';

export function getAreaCodeLevel(area_code) {
  return typeof area_code === 'string' && area_code.split('.').length;
}

function getSystemTitle(data = {}) {
  // 填写的系统假数据标题
  const staticData = useStaticDataStore();
  const system_name = get(staticData, 'data.system_name', '');
  if (system_name) return system_name;

  // 角色上支持修改系统名称了
  return (data && data.systemName) || '';
  // const { unitCode, systemName, areaName, type } = data;
  // const useSystemName = unitCode && unitCode.indexOf('@') >= 0;
  // if (useSystemName && systemName) return systemName;
  // return areaName ? areaName + (type == 2 ? '智慧小区' : '智慧治理平台') : '智慧治理平台';
}

const id = getStoreId('userInfo');
export const useUserInfoStore = defineStore(id, {
  state: () => ({
    userButtons: [],
    userData: {},
    areaCode: '',
    areaName: '',
  }),
  getters: {
    area_code: (state) => get(state, 'areaCode', ''),
    area_name: (state) => get(state, 'areaName', ''),
    unit_code: (state) => get(state, 'userData.unitCode', ''),
    unit_name: (state) => get(state, 'userData.unitName', ''),
    systemName: (state) => getSystemTitle(get(state, 'userData', {})),
    systemCode: (state) => get(state, 'userData.systemCode'),
    accountId: (state) => get(state, 'userData.accountId', ''),
    nickname: (state) => get(state, 'userData.nickname'),
    /* 超管账号 */
    isSuperUser: (state) => get(state, 'userData.type') === 0,
    /* 公司员工账号 */
    isEmployeeUser: (state) => get(state, 'userData.type') === 3,
    isSubArea: (state) => (area_code) => new RegExp(`^${state.area_code}`).test(area_code),
    isSubUnit: (state) => (unit_code) => new RegExp(`^${state.unit_code}`).test(unit_code),
    isUnitAccount(state) {
      return get(state, 'userData.type') === 1;
    },
    isUserAccount(state) {
      return get(state, 'userData.type') === 21;
    },
    isManager(state) {
      return [0, 3].includes(get(state, 'userData.type'));
    },
    isMine: (state) => (id) => get(state, 'userData.accountId') === id,
    isZzMine: (state) => (id) => get(state, 'userData.zz_people_id') === id,
    isForMe: (state) => (ids) => new RegExp(get(state, 'userData.accountId')).test(ids),
    isForZzMe: (state) => (ids) => new RegExp(get(state, 'userData.zz_people_id')).test(ids),
    /* 该账号 area_code 长度 */
    area_code_level: (state) => (area_code) => {
      return getAreaCodeLevel(area_code || get(state, 'areaCode'));
    },
    isHtBtnValid: (state) => get(state, 'userData.no_login_ht') === 1,
    avatarEncrypted: (state) => get(state, 'userData.img_encrypt_look', 1), // 0不加密、1加密
  },
  actions: {
    /* 这里的 Login , Logout 删除了, 用 views/login/utils.js 中的 login,logout 代替 */
    // 修改当前area_code - area_name
    updateAreaInfo(area_code, area_name) {
      this.areaCode = area_code;
      this.areaName = area_name;
    },
    // 情况用户信息 - 免登录会相互之间串
    clearUserData() {
      this.$reset();
    },
    // 获取用户信息
    async getUserInfoAsync() {
      if (!isEmpty(this.userData)) {
        return this.userData;
      }
      let data = storage.session.getItem(USER_INFO_KEY);
      if (isEmpty(data)) {
        data = await handleCommonRes(tokenDecrypt, null);
        data = Object.assign({}, data, data.tokenAccount);
        data.uuAccount = `${data.account}-${Date.now().toString(36)}`;
      }
      this.userData = data;
      this.areaCode = get(data, 'areaCode', '');
      this.areaName = get(data, 'areaName', '');
      storage.session.setItem(USER_INFO_KEY, data, { expires: 1 });
      setFavicon(data.systemIcon);
      setDocumentTitle(getSystemTitle(data));
    },
    // 获取按钮权限
    async getUserButtonsAsync() {
      if (!isEmpty(this.userButtons)) {
        return this.userButtons;
      }
      let data = storage.session.getItem(USER_BUTTONS_KEY);
      if (isEmpty(data)) {
        const $axios = vueGlobal.get('$axios');
        const api = (params) => $axios.get('/xw-microservice/xw-system/v3/menu/userMenuBtn', { params });
        data = await handleCommonRes(api);
      }
      let list = data.reduce((res, key) => {
        return res.includes(key) ? res : res.concat(key);
      }, []);
      this.userButtons = list;
      storage.session.setItem(USER_BUTTONS_KEY, list, { expires: 1 });
    },
  },
});
